<template>
    <div>
        <div ref="xgplayer"></div>
    </div>
</template>

<script>
export default {
    name: 'xgPlayer', //西瓜视频播放器
    props: {
        //绑定值
        value: {
            type:[String,Array,Object],
            default: function () {
                return '';
            }
        },
        config:{
            type:Object,
            default: function () {
                return {
                    height: '100%',
                    width: '100%',
                };
            }
        }

    },
    data() {
        return {
            player: null,
            intervalTime:null,
        }
    },

    computed: {
        use_config(){
            let config = this.copyObj(this.config);
            config.url = this.value;
            config.el = this.$refs.xgplayer;
            return config;
        }
    },
    methods: {
        copyObj(obj){
            return JSON.parse(JSON.stringify(obj));
        },
        initPlayer() {
            this.player = new window.Player(this.use_config);
            const Events = window.Player.Events;
            collect(Events).each((event) => {
                this.player.on(event, (data) => {
                    this.$emit(event,data);
                });
            });

        },
        destroyPlayer() {
            if(this.player){
                this.player.destroy();
                this.player = null;
            }else {
                clearInterval(this.intervalTime);
            }
        },
        updatePlayer() {
            if(this.player){
                this.player.setConfig(this.use_config);
                this.player.switchURL(this.use_config.url);
            }
        },
        pause(){
            if(this.player){
                this.player.pause();
            }
        }
    },
    watch: {
        value(newVal, oldVal) {
            this.updatePlayer();
            if(this.player){
                this.player.reset();
            }
        },
        config(newVal, oldVal) {
            this.updatePlayer();
        }
    },
    mounted() {
        this.intervalTime = setInterval(()=>{
            if(typeof window.Player=="function"){
                clearInterval(this.intervalTime);
                this.initPlayer();
            }
        },100);
    },
    beforeDestroy() {
        this.destroyPlayer();
    },
    created() {
        //动态加载js文件
        if(!document.getElementById('xgplayer')){
            let $script = document.createElement('script');
            $script.id = 'xgplayer';
            $script.type = 'text/javascript';
            $script.src = '/bower_components/xgplayer/index.min.js';
            $script.async = false;
            document.body.appendChild($script);
        }
    },



}
</script>

<style lang="scss">
@import url('/bower_components/xgplayer/index.min.css');
</style>
